package cn.com.doone.common.uc.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Iterator;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

public class FileUtils {

	public static File uploadFile(HttpServletRequest request,String targetUrl) throws Exception{
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		if (!multipartResolver.isMultipart(request)) {
			return null;
		}
		MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
		Iterator<String> iter = multiRequest.getFileNames();
		while (!iter.hasNext()) {
			return null;
		}
		MultipartFile file = multiRequest.getFile(iter.next());
		if (file == null) {
			return null;
		}
		String fileName = file.getOriginalFilename(); // 文件名,包括扩展名
		String[] str = fileName.split("\\.");
		if (str.length != 2) {
			throw new Exception("未知的文件格式");
		}
		String extensionName = str[1]; // 扩展名
		if (!"zip".equals(extensionName)) {
			throw new Exception("文件不是zip格式");
		}
		
		File target = new File(targetUrl);
		if (!target.exists() && !target.isDirectory()) {
			target.mkdirs();
		}
		
		File targetFile = new File(target, fileName);
		if (!targetFile.exists()) {
			targetFile.createNewFile();
		}
		file.transferTo(targetFile);
		return targetFile;
	}

	/**
	 * 解压zip文件
	 * 
	 * @param zipFile
	 *            压缩文件
	 * @param unZipPath
	 *            解压路径
	 */
	public static void unzip(File zipFile, String unZipPath) throws Exception {

		String fileName = zipFile.getName();
		String[] fileNames = fileName.split("\\.");
		if (fileNames.length != 2) {
			throw new Exception("未知的文件格式");
		}
		if (!"zip".equals(fileNames[1])) {
			throw new Exception("文件不是zip格式");
		}
		ZipInputStream zin = new ZipInputStream(new FileInputStream(zipFile));
		BufferedInputStream bin = new BufferedInputStream(zin);
		File fout = null;
		ZipEntry entry;
		while ((entry = zin.getNextEntry()) != null && !entry.isDirectory()) {
			fout = new File(unZipPath, entry.getName());
			if (!fout.exists()) {
				new File(fout.getParent()).mkdirs();
			}
			FileOutputStream out = new FileOutputStream(fout);
			BufferedOutputStream bout = new BufferedOutputStream(out);
			int b;
			while ((b = bin.read()) != -1) {
				bout.write(b);
			}
			bout.close();
			out.close();
		}
		bin.close();
		zin.close();
	}

}
